package com.tobeing.voicechat.customs;

import android.media.MediaRecorder;
import android.util.Log;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2017/10/31/031.
 */

public class RecorderManager {
    private static RecorderManager mInstance;
    private MediaRecorder mMediaRecorder;
    private String mFileDir;
    private String mCurrentPath;
    private RecorderPrepareListener mListener;

    public RecorderManager(String dir) {
        mFileDir = dir;
    }

    public interface RecorderPrepareListener {
        void prepared();
    }

    public static RecorderManager getInstance(String dir) {
        if (mInstance == null) {
            synchronized (RecorderManager.class) {
                if (mInstance == null) {
                    mInstance = new RecorderManager(dir);
                }
            }
        }
        return mInstance;
    }

    public void prepareRecorder() {
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();
        }
        try {
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            File dir = new File(mFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, getFileName());
            mCurrentPath = file.getAbsolutePath();
            Log.i("path", mCurrentPath);
            mMediaRecorder.setOutputFile(mCurrentPath);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            if (mListener != null) {
                mListener.prepared();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getFileName() {
        return System.currentTimeMillis() + ".arm";
    }

    public String getCurrentPath(){
        return mCurrentPath;
    }

    public void setRecorderPrepareListener(RecorderPrepareListener listener) {
        mListener = listener;
    }

    public int getVoiceLevel(int maxLevel) {
        if(mMediaRecorder != null) {
            return maxLevel * mMediaRecorder.getMaxAmplitude() / 12368 + 1;
        }else {
            return 1;
        }
    }

    public void cancelRecorder() {
        releaseRecorder();
        if(mCurrentPath != null){
            File file = new File(mCurrentPath);
            file.delete();
            mCurrentPath = null;
        }
    }

    public void releaseRecorder() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }
}
